using System;
using System.Globalization;
using System.Collections;
using UnityEngine;
// 玩家控制器，管理角色的行为、状态转换等
public class PlayerController : CharacterBase<PlayerController>
{
    public float mouseSpeed;
    public float verticalSpeed;
    public GameObject mainCamera;
    public MouseInputReader mouseInputReader { get; private set; }
    public MoveInputReader moveInputReader { get; private set; }
    private Vector3 lastLookDirection = Vector3.forward;
    public float cameraOffsetY = 0;
    public int JumpForce;
    public TouchEnmeyEvent touchEnemyComp;
    public float rayDistance;
    private PlayAudioComp playAudioComp;

    // private BottomTouchGroundEvent TouchGroundEvent;

    //无敌帧
    public bool isInvincible { get; set; }
    //无敌帧秒
    float invincibilityTime;
    private float blinkTimer;

    //外部设置无敌帧秒数
    public float invincibilityDuration;
    private SpriteRenderer spriteRenderer;

    protected override void Init()
    {
        GameManager.Instance.Player = gameObject;
        mouseInputReader = new MouseInputReader(mainCamera, mouseSpeed, verticalSpeed, gameObject);
        moveInputReader = new MoveInputReader(mouseInputReader);
        InputSource = new PlayerReaderSource(moveInputReader, mouseInputReader);
        // TouchGroundEvent = transform.Find("ButtomCollider").GetComponent<BottomTouchGroundEvent>();
        playAudioComp = GetComponent<PlayAudioComp>();
    }

    protected override void onStart()
    {
        characterStateMachine.Initialize(new CharacterIdleState<PlayerController>(this, characterStateMachine), CharacterAnimation);
        spriteRenderer = GetComponent<SpriteRenderer>();
    }
    protected override void Enable()
    {
        mouseInputReader.OnEnable();
        moveInputReader.OnEnable();
    }
    protected override void Disable()
    {
        mouseInputReader.OnDisable();
        moveInputReader.OnDisable();
    }

    protected override void onUpdate()
    {
        moveInputReader.Update();
        mainCamera.transform.localPosition = new Vector3(transform.position.x, transform.position.y + cameraOffsetY, transform.position.z - 10); // 相机相对偏移

        //检测无敌帧
        isInvincibling();
        //是否闪烁
        UpdateBlink();
    }
    //闪烁中
    void UpdateBlink()
    {
        if (isInvincible)
        {
            blinkTimer -= Time.deltaTime;
            // 每0.1秒切换显示状态
            float blinkProgress = blinkTimer % (0.1f * 2);
            spriteRenderer.enabled = blinkProgress > 0.1f;
        }
    }
    //开始无敌帧
    public void StartInvincibility()
    {
        isInvincible = true;
        invincibilityTime = invincibilityDuration;
        blinkTimer = invincibilityDuration;
    }
    //是否无敌帧
    private void isInvincibling()
    {
        if (isInvincible)
        {
            invincibilityTime -= Time.deltaTime;
            if (invincibilityTime <= 0)
            {
                isInvincible = false;
                spriteRenderer.enabled = true;
            }
        }
    }

    protected override void onFixedUpdate()
    {
        mouseInputReader.Update();
        // MoveCharacter();

    }
    //触碰敌人
    internal void setTouchEnemyComp()
    {
        Transform touchhit = transform.Find("TouchHit");
        if (touchhit == null) return;
        touchEnemyComp = touchhit.GetComponent<TouchEnmeyEvent>();
    }

    //是否落地
    private bool IsGrounded()
    {
        RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, rayDistance, LayerMask.GetMask("ground"));
        return hit.collider != null;
    }
    //角色跳跃独特逻辑
    public virtual void Jump()
    {
        playAudioComp.PlayJumpAudio();
        SetJumpForce(GetJumpForce());
        rb.AddForce(Vector2.up * GetJumpForce() / 5, ForceMode2D.Impulse);
    }
    //设置跳跃的力
    public void SetJumpForce(int value)
    {
        JumpForce = value;
    }
    //获取跳跃的力
    public int GetJumpForce()
    {
        return JumpForce;
    }
    //在空中
    public void Jumping()
    {
        // TouchGroundEvent.isGround = false;
        CharacterAnimation.VelocityY = rb.velocity.y;
        CharacterAnimation.jumpAnim();
    }
    //落地后的设置
    internal bool IsFalling()
    {
        if (characterStateMachine.CurrentState is CharacterJumpState<PlayerController>)
        {
            touchEnemyComp = transform.Find("TouchHit").GetComponent<TouchEnmeyEvent>();
            if (touchEnemyComp)
                if (IsGrounded())
                {
                    // CharacterAnimation.PlayJumpEndAnim();
                    // StopAllActions();
                    CharacterAnimation.VelocityY = -400;
                    CharacterAnimation.jumpAnim();
                    return true;
                }
        }
        return false;
    }

    //死亡
    public override void Die()
    {
        //死亡音效
        playAudioComp.Lose();

    }
    //角色死亡独特逻辑 由角色死亡动画帧事件调用
    public void PlayerDie()
    {

        // Time.timeScale = 0f;
        //角色死亡，弹出游戏失败提示框 完成游戏逻辑闭环
        // Debug.Log("死亡提示框");
        GameManager.Instance.OpenLoseUI();
    }
    //移动方向
    public override void MoveCharacter()
    {
        float Direction = moveInputReader.Forward.x;
        if (moveInputReader.Forward.x != 0)
        {
            transform.localScale = new Vector3(Direction, 1, 1);
        }
        transform.position = new Vector3(transform.position.x + moveInputReader.Forward.x * moveSpeed, transform.position.y, transform.position.z);
    }
    //播放攻击音频
    public void playAttackAudio()
    {
        playAudioComp.PlayAttackAudio();
    }
    //行走的方向 用放大倍数设置的
    public override void AttackRepel()
    {
        if (transform.localScale.x > 0)
        {
            rb.AddForce(Vector2.left * 10, ForceMode2D.Impulse);
        }
        else
        {
            rb.AddForce(Vector2.right * 10, ForceMode2D.Impulse);
        }
    }

    public void AddHealthVFX()
    {
        playAudioComp.PlayAddHealthAudio();
        transform.Find("AddHealthEffect").gameObject.SetActive(true);
    }
}
